package controllers

import (
	"Myshop/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
	"math"
	"strconv"
	"time"
)

type OrderController struct {
	beego.Controller
}

func (this *OrderController) ShowOrder() {
	skuids := this.GetStrings("skuid")
	user := GetUserName(&this.Controller)
	if user == "" {
		beego.Info("未登录！")
		return
	}

	o := orm.NewOrm()
	var userM models.User
	userM.Name = user
	o.Read(&userM, "Name")

	goodsMap := make([]map[string]interface{}, len(skuids))
	conn, err := redis.Dial("tcp", ":6379")
	if err != nil {
		beego.Info("redis出错！")
		return
	}
	allPrice := 0
	allCount := 0
	for i, val := range skuids {
		tmp := make(map[string]interface{})
		id, _ := strconv.Atoi(val)

		//从redis中获取对应商品个数
		goodsCount, err := conn.Do("hget", "cart_"+strconv.Itoa(userM.Id), id)

		count, err := redis.Int(goodsCount, err)
		if err != nil {
			beego.Info("数据获取失败！")
			return
		}
		var goods models.GoodsSKU
		goods.Id = id
		o.Read(&goods, "Id")

		tmp["count"] = count
		tmp["amount"] = count * goods.Price
		tmp["goods"] = goods

		allCount += count
		allPrice += count * goods.Price

		goodsMap[i] = tmp
	}

	var address []models.Address
	o.QueryTable("Address").RelatedSel("User").Filter("User__Id", userM.Id).All(&address)

	this.Data["addr"] = address
	this.Data["totalCount"] = allCount
	this.Data["totalPrice"] = allPrice
	this.Data["transferPrice"] = math.Ceil(float64(allPrice) * 0.01)
	this.Data["realyPrice"] = float64(allPrice) + math.Ceil(float64(allPrice)*0.01)
	this.Data["goodsBuffer"] = goodsMap
	this.TplName = "place_order.html"
}
func (this *OrderController) AddOrder() {
	addrId, _ := this.GetInt("addrId")
	pay, _ := this.GetInt("payId")
	//idsS := this.GetString("skuids")
	//skuids := strings.Split(idsS," ")
	//beego.Info("skuids--------->:",skuids)
	//skuids := ids[1:]
	//totalPrice,_ := this.GetInt("totalPrice")
	transferPrice, _ := this.GetInt("transferPrice")
	realyPrice, _ := this.GetInt("realyPrice")
	totalCount, _ := this.GetInt("totalCount")
	resp := make(map[string]interface{})
	defer this.ServeJSON()

	user := GetUserName(&this.Controller)
	if user == "" {
		resp["code"] = 2
		resp["errmsg"] = "未登录"
		this.Data["json"] = resp
		return
	}
	o := orm.NewOrm()
	o.Begin()
	var userM models.User
	userM.Name = user
	o.Read(&userM, "Name")
	var address models.Address
	address.Id = addrId
	o.Read(&address)
	var orderInfo models.OrderInfo
	orderInfo.OrderId = time.Now().Format("20120301030405") + strconv.Itoa(userM.Id)
	orderInfo.User = &userM
	orderInfo.Address = &address
	orderInfo.Orderstatus = 1
	orderInfo.PayMethod = pay
	orderInfo.TotalCount = totalCount
	orderInfo.TotalPrice = realyPrice
	orderInfo.TransitPrice = transferPrice
	o.Insert(&orderInfo)

	conn, err := redis.Dial("tcp", ":6379")
	if err != nil {
		beego.Info("链接失败redis！")
		return
	}
	defer conn.Close()
	sku, err := conn.Do("hgetall", "cart_"+strconv.Itoa(userM.Id))
	skuids, err := redis.IntMap(sku, err)

	for skuid, val := range skuids {
		//skuid, _ := strconv.Atoi(val)
		//gcount, err := conn.Do("hget", "cart_"+strconv.Itoa(userM.Id), skuid)

		//gCount, err := redis.Int(gcount, err)
		if err != nil {
			resp["code"] = 3
			resp["errmsg"] = "数据获取出错！"
			this.Data["json"] = resp
			return
		}
		var goods models.GoodsSKU
		goods.Id, _ = strconv.Atoi(skuid)
		i := 3

		o.Read(&goods)
		for i > 0 {
			if val > goods.Stock {
				resp["code"] = 2
				resp["errmsg"] = goods.Name + "库存不足"
				this.Data["json"] = resp
				beego.Info("回滚了——————>")
				o.Rollback()
				return
			}
			precount := goods.Stock
			goods.Stock -= val
			goods.Sales += val
			updateCount, _ := o.QueryTable("GoodsSKU").Filter("Id", goods.Id).Filter("Stock",
				precount).Update(orm.Params{"Stock": goods.
				Stock, "Sales": goods.Sales})

			var orderGoods models.OrderGoods
			orderGoods.GoodsSKU = &goods
			orderGoods.OrderInfo = &orderInfo
			orderGoods.Price = val * goods.Price
			orderGoods.Count = val
			o.Insert(&orderGoods)
			if updateCount == 0 {
				if i > 0 {
					i -= 1
					continue
				}
				resp["code"] = 2
				resp["errmsg"] = goods.Name + "商品库存变化"
				this.Data["json"] = resp
				o.Rollback()
				return
			} else {
				conn.Do("hdel", "cart_"+strconv.Itoa(userM.Id), goods.Id)
				break
			}
		}
	}
	o.Commit()
	resp["code"] = 5
	resp["errmsg"] = "ok"
	this.Data["json"] = resp
}
